<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/16 17:49
 */

namespace App\Http\Controllers;

use App\Http\Models\Goods;
use App\Http\Models\GoodsCoupon;
use App\Http\Models\GoodsShop;
use App\Http\Models\DescribeRule;
use App\Http\Models\GoodsKill;
use App\Http\Models\GoodsSales;
use App\Http\Models\GoodsAudit;
use App\Http\Models\User;
use App\Http\Models\UserAuth;
use App\Http\Models\UserCapital;
use App\Http\Models\StatisticsUserKill;
use App\Http\Models\StatisticsGoodsInfoLog;
use App\Http\Models\UserKillStatus;
use App\Http\Models\StatisticsUser;
use App\Http\Models\UserSubmitAudit;
use App\Http\Models\UserIntegralLog;
use App\Http\Models\StatisticsGoodsInfo;
use App\Http\Models\VoucherLog;
use Illuminate\Support\Facades\Cache;
use Auth;
use DB;
use Carbon\Carbon;
use function PHPSTORM_META\type;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests\KillRequest;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;

class KillController extends Controller
{
    /**
     * 增加秒杀商品
     */
    public function saveKillGood(KillRequest $request)
    {
        $goodData = $request->only(['coverimage', 'goodstitle', 'voucherprice', 'commissionrate', 'commissiontype', 'copywritingimage', 'goodslink', 'copywriting',]);
        $killdata = $request->only(['startdate', 'startfield', 'keyword', 'content', 'friends']);
        $goods_coupon = $request->only(['couponmoney', 'coupontype', 'coupontotal', 'couponlink', 'couponstarttime', 'couponendtime']);
        $goods_shop = $request->only(['activitytype']);
        //$goodData["copywriting"] = ['wenan1' => $goodData["copywriting"]];
        //$goodData["copywritingimage"] = ['first'=>$goodData["copywritingimage"]]; //explode(',', str_replace('，', ',', $goodData["copywritingimage"]));
        if (!$killdata['startdate']) {
            $killdata['startdate'] = date('Y-m-d', time());
        }
        $goodslink = $goodData['goodslink'];
        preg_match_all("/(?<=(\?|&)id=)\w+/i", $goodData['goodslink'], $match);
        if (empty($match[0][0])) {
            return json_encode(['code' => 1, 'msg' => 'link参数不正确，未包含正确的商品ID！']);
        }
        $goodid = $match[0][0];
        $goodData['goodslink'] = substr($goodslink, 0, stripos($goodslink, '?')) . '?id=' . $goodid;
        if (strtotime($killdata['startdate']) < time() + 3) {  //开始时间不能大于当前时间
            return json_encode(['code' => 1, 'msg' => '秒杀开始时间已过,请修改秒杀时间!']);
        }
        if (is_array($killdata['keyword'])) {
            $keyword = $killdata['keyword'];
        } else {
            $keyword = json_decode($killdata['keyword'], true);
        }
        $gid = request('id');
        if (empty($keyword)) {
            return json_encode(['code' => 1, 'msg' => 'keyword不是有效的json数据!']);
        }
        if (empty($gid)) {
            if (!UserCapital::IsSendGoods(2)) {
                return json_encode(['code' => 1, 'msg' => '用户积分扣完或点券已用完,请确认!']);
            }
        }
        $new_keyword = [];
        if ($keyword) {
            foreach ($keyword as $key => $value) {
                $new_keyword[] = $value['value'];
            }
            $killdata['keyword'] = implode(',', array_values($new_keyword));
        }

        //根据goodsid 通过 SDK调用API接口 获取商品信息
        $taobaoinfo = Goods::getTaobaoGoodsInfo($goodid);
        if (isset($taobaoinfo['error_response']) || (isset($taobaoinfo['code']) && $taobaoinfo['code'] != 0)) {
            return json_encode(['code' => 1, 'msg' => '商品信息有误!']);
        }
        $goods_shop_info = $taobaoinfo['results']['n_tbk_item'];
        $goods = Goods::where(['goodsid' => $goods_shop_info['num_iid'], 'goodsstate' => 2])->first();
        if ($goods && $goods->userid > 10000) {
            return json_encode(['code' => 1, 'msg' => '该商品已经正在做活动,不能参与活动!']);
        }
        $shop_info = [
            'shoptype' => $goods_shop_info['user_type'],
            'shopname' => $goods_shop_info['nick'],
        ];
        //对应goods_sales
        $goods_sales = [
            'startsales' => (int)$request->input('startsales'),
            'monthsales' => $goods_shop_info['volume']
        ];

        $killdata['user_id'] = Auth::id();
        if (!empty($gid)) {
            $goods_info = Goods::where(['id' => $gid])->first();
            if ($goods_info->goodsstate == 2) {
                return json_encode(['code' => 1, 'msg' => '审核通过的商品不能再修改!']);
            }
            DB::beginTransaction();
            // $goodData["goodsstate"] = 0;
            $gid = Goods::addKillGood($goodData, $goods_shop_info, $goodid, $gid);
            $goods_coupon_bool = GoodsCoupon::where(['gid' => $gid])->update(array_merge($goods_coupon, ['gid' => $gid]));
            $killdata_bool = GoodsKill::where(['gid' => $gid])->update(array_merge($killdata, ['gid' => $gid,]));
            $goods_sa = GoodsSales::where(['gid' => $gid])->first();
            $goods_sa->startsales = $goods_sales['startsales'];
            $goods_sales_bool = $goods_sa->save();
            $cap_log = true;
            //点券消费
            if ($goods_info->goodsstate == 3) {
                $content = '秒杀商品[' . $goods_info->goodstitle . ']修改再次发布,使用' . env('Voucher_Kill_Deduct') . '点券';
                $cap_log = UserCapital::addUserCapital(Auth::id(), env('Voucher_Kill_Deduct'), 0, $content, $gid);
                $goods_info->goodsstate = 0;
                $goods_info->save();
                /*   //个人用户统计
                   StatisticsUserKill::updateUserKill(Auth::id(), 0);
                   //增加秒杀商品统计更新
                   StatisticsGoods::updateStatisticsGoods(2, 0);
                   //增加秒杀商品统计更新
                   StatisticsGoodsToday::updateNewOrder(2);*/
                StatisticsGoodsInfo::updateStatisticsGoods($gid, $goods_info->goodstype, 0, 0, $goods_info->created_at, 3);
            }
            if ($gid && $cap_log && $goods_coupon_bool && $killdata_bool && $goods_sales_bool) {
                DB::commit();
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => '秒杀数据修改成功,请等待审核!', 'data' => $user]);
            } else {
                DB::rollBack();
                return json_encode(['code' => 1, 'msg' => '秒杀数据修改失败!']);
            }
        } else {
            DB::beginTransaction();
            $gid = Goods::addKillGood($goodData, $goods_shop_info, $goodid);
            $goods_coupon_bool = GoodsCoupon::create(array_merge($goods_coupon, ['gid' => $gid]));
            $killdata_bool = GoodsKill::create(array_merge($killdata, ['gid' => $gid]));
            $shop_bool = GoodsShop::create(array_merge($goods_shop, ['gid' => $gid], $shop_info));
            $goods_sales_bool = GoodsSales::create(array_merge($goods_sales, ['gid' => $gid]));

            $user_goods_number = Goods::where(['userid' => Auth::id()])->count();
            if ($user_goods_number <= 1) {
                StatisticsUser::updateOrderNum(); //增加下单用户数量
            }
            $content = '秒杀商品[' . Goods::where(['id' => $gid])->first()->goodstitle . ']发布,使用' . env('Voucher_Kill_Deduct') . '点券';
            $cap_log = UserCapital::addUserCapital(Auth::id(), env('Voucher_Kill_Deduct'), 0, $content, $gid);
            if ($cap_log && $gid && $goods_coupon_bool && $killdata_bool && $shop_bool && $goods_sales_bool) {
                DB::commit();
                /*   //个人用户统计
                   StatisticsUserKill::updateUserKill(Auth::id(), 0);
                   //增加秒杀商品统计更新
                   StatisticsGoods::updateStatisticsGoods(2, 0);
                   //增加秒杀商品统计更新
                   StatisticsGoodsToday::updateNewOrder(2);*/
                $goods_info = Goods::where(['id' => $gid])->first();
                StatisticsGoodsInfo::updateStatisticsGoods($gid, $goods_info->goodstype, 0, 0, $goods_info->created_at, -1);
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => '秒杀数据增加成功,请等待审核!', 'data' => $user]);
            } else {
                DB::rollBack();
                return json_encode(['code' => 1, 'msg' => '秒杀数据增加失败!']);
            }
        }

    }

    /**
     * 获取秒杀规则
     * @return string
     */
    public function getKillRule(Request $request)
    {
        $page = request('page') ? request('page') : 1;
        $list = Cache::remember('getKillRule:' . $page, 10, function () use ($request) {
            return DescribeRule::select('content')->where(['type' => 2])->paginate(env('LIMIT'));
        });
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $list]);
    }

    /**
     * 获取秒杀平台数据
     * @return string
     */
    public function getKillData()
    {
        /*  $userkillData = StatisticsUserKill::select('conduct_number', 'submission_number', 'refuse_number', 'wait_number')
              ->where(['user_id' => Auth::id()])->first();
          if ($userkillData) {
              $killConductNumber = $userkillData->conduct_number;
              $killSubmissionNumber = $userkillData->submission_number;
              $killRefuseNumber = $userkillData->refuse_number;
              $killWaitNumber = $userkillData->wait_number;
          } else {
              $killConductNumber = 0;
              $killSubmissionNumber = 0;
              $killRefuseNumber = 0;
              $killWaitNumber = 0;
          }*/
        $uid = Auth::id();
        $killConductNumber = Goods::where(['userid' => $uid, 'goodsstate' => 2, 'couponstate' => 0, 'goodstype' => 2])->count();
        $killSubmissionNumber = Goods::where(['userid' => $uid, 'goodstype' => 2])->count();
        $killRefuseNumber = Goods::where(['userid' => $uid, 'goodsstate' => 3, 'goodstype' => 2])->count();
        $killWaitNumber = Goods::where(['userid' => $uid, 'goodsstate' => 0, 'goodstype' => 2])->count();
        $KillData = [
            'killConductNumber' => $killConductNumber,
            'killSubmissionNumber' => $killSubmissionNumber,
            'killRefuseNumber' => $killRefuseNumber,
            'killWaitNumber' => $killWaitNumber
        ];
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $KillData]);
    }

    /**
     * 获取秒杀商品的审核动态
     */
    public function getKillDataDynamic(Request $request)
    {
        $page = request('page') ? request('page') : 1;
        $list = Cache::remember('getKillDataDynamic:' . Auth::id() . ':' . $page, 2, function () use ($request) {
            return GoodsAudit::select('title', 'state', 'created_at', 'content')
                ->where(['user_id' => Auth::id(), 'goodstype' => 2])
                ->where('state', '>', 0)
                // ->whereBetween('state', [2, 0])
                ->paginate(env('LIMIT'));
        });
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $list]);
    }

    /**
     * 获取秒杀商品的信息
     */
    public function getKillGoodInfo(Request $request)
    {
        $id = $request->id;

        if (empty($id)) {
            return json_encode(['code' => 1, 'msg' => '无效id', 'data' => '']);
        }
        $data = GoodsKill::leftjoin('goods', 'goods.id', '=', 'goods_kill.gid')
            ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
            ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
            ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
            ->select('goods_kill.keyword', 'goods_kill.content', 'goods_kill.startdate', 'goods_kill.startfield', 'goods_kill.friends',
                'goods.id as id', 'goods.goodsid', 'goods.coverimage', 'goods.goodstitle', 'goods.voucherprice', 'goods.commissionrate', 'goods.commissiontype', 'goods.copywritingimage', 'goods.goodslink', 'goods.copywriting',
                'goods_coupon.coupontype', 'goods_sales.startsales', 'goods_coupon.couponmoney', 'goods_coupon.coupontotal', 'goods_coupon.couponlink', 'goods_coupon.couponstarttime', 'goods_coupon.couponendtime'
                , 'goods_shop.activitytype'
            )
            ->where(['goods.id' => $id])->first();

        if ($data) {
            if (is_array($data->keyword)) {
                $keyword = json_decode($data->keyword, true);
                foreach ($keyword as $key => $value) {
                    $new_keyword[] = ["key" => $key + 1, "value" => $value];
                }
                $data->keyword = $new_keyword;// implode(',', $keyword);
            } else {
                $keyword = explode(',', str_replace('，', ',', $data->keyword));
                foreach ($keyword as $key => $value) {
                    $new_keyword[] = ["key" => $key + 1, "value" => $value];
                }
                $data = $data->toArray();
                $data['keyword'] = $new_keyword;// implode(',', $keyword);
            }
        }
        if (empty($data)) {
            return json_encode(['code' => 1, 'msg' => '暂无数据', 'data' => '']);
        }
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $data]);

    }


    /**
     * 对秒杀商品进行下架
     */
    public function LowerFrameGood()
    {
        $id = request('id');
        $status = request('status');
        if (!$id && in_array($status, [5, 6])) {
            return json_encode(['code' => 1, 'msg' => '无效id,或状态值', 'data' => '']);
        }
        DB::beginTransaction();
        $goods = Goods::where(['id' => $id, 'userid' => Auth::id()])->first();//find($id);
        if (!$goods) {
            return json_encode(['code' => 1, 'msg' => '无效id', 'data' => '']);
        }
        if (in_array($goods->goodsstate, [3, 4, 5, 6])) {
            return json_encode(['code' => 1, 'msg' => '该商品已撤销或已拒绝,下架,不能撤销或下架', 'data' => '']);
        }
        $old_type = $goods->goodsstate;
        $goods->goodsstate = $status;
        $bool = $goods->save();
        $cap_log = true;
        //撤回
        if ($status == 5) {
            $content = '秒杀商品[' . $goods->goodstitle . ']审核撤回,退回' . env('Voucher_Kill_Deduct') . '点券';
            $cap_log = UserCapital::addUserCapital($goods->userid, env('Voucher_Kill_Deduct'), 1, $content, $goods->id);
            /*//个人用户统计
            StatisticsGoods::updateStatisticsGoods($goods->goodstype, 3);
            //增加秒杀商品统计更新
            if ($goods->goodstype == 2) {
                StatisticsUserKill::updateUserKill(Auth::id(), 3);
            }
            //统计用户在线商品状态
            StatisticsUserKill::addUserOnlineGood(Auth::id(), 3);*/
        } else {
            /*      //个人用户统计
                  if ($goods->goodstype == 2) {
                      StatisticsUserKill::updateUserKill(Auth::id(), 4);
                  }
                  //增加秒杀商品统计更新
                  StatisticsGoods::updateStatisticsGoods($goods->goodstype, 4);
                  //统计用户在线商品状态
                  StatisticsUserKill::addUserOnlineGood(Auth::id(), 4);*/
        }
        //($gid, $type, $change_type, $operation_type, $create_at = '', $old_type = -1, $is_no_error = true, $num = 1)
        StatisticsGoodsInfo::updateStatisticsGoods($id, $goods->goodstype, $status, 0, $goods->created_at, $old_type);
        if ($bool && $cap_log) {
            DB::commit();
            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => '']);
        } else {
            DB::rollBack();
            return json_encode(['code' => 1, 'msg' => 'ng', 'data' => '']);
        }
    }


    /**
     * 获取用户的秒杀未审核/审核/拒绝的信息
     * @param Request $request
     * @return string
     */
    public function getUserKillList(Request $request)
    {
        $type = $request->type;
        if (!in_array($type, ['allow', 'refuse', 'unaudited'])) {
            return json_encode(['code' => 1, 'msg' => '不存在此分类', 'data' => '']);
        }
        $state = $type == 'allow' ? [2, 4, 6, 8] : ($type == 'refuse' ? [3] : [0]);
        $list = DB::table('goods')
            ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
            ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
            ->leftjoin('goods_kill', 'goods.id', '=', 'goods_kill.gid')
            ->leftjoin('users', 'goods.userid', '=', 'users.id')
            ->leftjoin('goods_shop', 'goods_shop.gid', '=', 'goods.id')
            ->select('users.name as username',
                'goods_sales.startsales', 'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.zerosales', 'goods_sales.todaysales',
                'goods_coupon.couponlink', 'goods_coupon.coupontype', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.couponstarttime', 'goods_coupon.couponendtime', 'goods_coupon.couponcondition', 'goods_coupon.reduceprice',
                'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype',
                'goods.id', 'goods.userid', 'goods.goodsid', 'goods.goodslink', 'goods.goodstitle', 'goods.goodstype', 'goods.goodsstate', 'goods.coverimage', 'goods.commissiontype',
                'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.couponstate', 'goods.origprice', 'goods.voucherprice', 'goods.refuse', 'goods.commissiontype'
                , 'goods_kill.keyword', 'goods_kill.content', 'goods_kill.startdate', 'goods_kill.startfield', 'goods_kill.friends', 'goods_kill.comment', 'goods_kill.viewcount'
            )
            ->where(['goods.userid' => Auth::id(), 'goods.goodstype' => 2])
            ->whereIn('goods.goodsstate', $state)
            ->paginate(env('LIMIT'));
        $list = $list->toArray();
        foreach ($list['data'] as $key => $value) {
            if (is_object($value)) {
                $list['data'][$key] = object_array($value);
            } else {
                $list['data'][$key] = $value;
            }
        }
        foreach ($list['data'] as $key => $value) {
            $list['data'][$key]['keyword'] = keyword_array($value['keyword']);
        }
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $list]);
    }

    /**
     * 商品链接检测，是否包含已经上线的商品
     * @param Request $request
     * @return string
     */
    public function checkLink()
    {
        $link = $this->request->link;
        if (empty($link)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的link参数！']);
        }
        $partner = "/(?<=(\?|&)id=)\w+/i";
        preg_match_all($partner, $link, $match);
        if (empty($match[0][0])) {
            return json_encode(['code' => 1, 'msg' => 'link参数不正确，未包含正确的商品ID！']);
        }
        $goodid = $match[0][0];
        if (empty($goodid)) {
            return json_encode(['code' => 1, 'msg' => 'link参数中商品ID不正确！']);
        }
        $datas = Goods::select('goodsid', 'voucherprice')->where(array('goodsid' => $goodid, 'goodsstate' => 2, 'couponstate' => 0))->orderBy('voucherprice', 'asc')->first();
        if (!$datas) {
            return json_encode(['code' => 0, 'msg' => '验证通过!', 'data' => $datas]);
        } else {
            return json_encode(['code' => 1, 'msg' => '已经有商品正在做活动,不能再次添加!', 'data' => $datas]);
        }
        die;
    }

    protected function moreImage($string)
    {

        //copywritingimage
        $string = str_replace('，', ',', $string);
        $array = explode(',', str_replace('，', ',', $string));
        return $array;
    }

    public function test()
    {

       $res= DB::table('goods_sales')
            //->whereDate('updated_at', date('Y-m-d',strtotime('-1 week')))
            ->where('updated_at', '<',date('Y-m-d H:i:s',strtotime(date('Y-m-d').' 00:00:00')-7*24*3600))
            ->get()->toArray();
       dd($res);
        die;
        $goodslink = 'https://market.m.taobao.com/apps/abs/10/177/3jpyp?id=a21bo.2017.201862-1.d1.172811d9ZSJBsr&pos=1&_wvUseWKWebView=YES&psId=1656022&acm=20140506001.1003.2.4631764&scm=1003.2.20140506001.OTHER_1541307177382_4631764';
        preg_match_all("/(?<=(\?|&)id=)\w+/i", $goodslink, $match);
        $goodid = $match[0][0];
        $link = substr($goodslink, 0, stripos($goodslink, '?')) . '?id=' . $goodid;
        return json_encode(['code' => 1, 'msg' => '商品链接太长了,请更换！', 'data' => ['goodslink' => $link]]);

        die;
        echo phpinfo();
        die;
        DB::table('statistics_goods_info')->truncate();
        $error = StatisticsGoodsInfo::lastModel(0);
        $error = StatisticsGoodsInfo::lastModel(1);
        $error = StatisticsGoodsInfo::lastModel(2);
        $error = StatisticsGoodsInfo::lastModel(3);
        DB::table('statistics_goods_info_log')->truncate();
        die;
        /*  $model = StatisticsGoodsToday::where(['date' => date('Ymd')])->first();
          $model->increment('today_ordinary_unaudited');
          $model->save();
          die;*/
        $release_number = VoucherLog::where(['user_id' => 11935, 'status' => 0])
            ->whereDate('created_at', date('Ymd'))
            ->sum('number');
        $refuse_number = VoucherLog::where(['user_id' => 11935, 'status' => 1])
            ->leftjoin('goods', 'users_voucher_log.goods_id', '=', 'goods.id')
            ->whereDate('goods.created_at', date('Ymd'))
            ->whereMonth('users_voucher_log.created_at', date('m'))
            ->sum('number');
        //月
        $release_month_number = VoucherLog::where(['user_id' => 11935, 'status' => 0])
            ->whereMonth('created_at', date('m'))
            ->sum('number');
        $refuse_month_number = VoucherLog::where(['user_id' => 11935, 'status' => 1])
            ->leftjoin('goods', 'users_voucher_log.goods_id', '=', 'goods.id')
            ->whereMonth('goods.created_at', date('m'))
            ->whereMonth('users_voucher_log.created_at', date('m'))
            ->sum('number');
        dd($release_month_number - $refuse_month_number);
        $data = StatisticsGoodsInfo::getGoodsAllData();
        dd($data);
        die;

        $user = Goods::select('userid')->distinct()->get();
        if ($user) {
            $userids = $user->toArray();
            $userids = array_column($userids, 'userid');
        } else {
            $userids = [];
        }
        dd($userids);
        $query = User::select('phone');
        $a = request('phone');
        isset($a) && !empty($a) && $query->where('phone', $a);
        $b = request('name');
        isset($b) && !empty($b) && $query->where('name', $b);
        $data = $query->paginate(20)->toArray();
        dd($data);
        die;
        $year = 2000;
        $month = 10;
        $day = 20;
        $abc = sprintf("%04d-%02d-%02d", $year, $month, $day);
        //$abc = str_pad($number, 6, '0', STR_PAD_LEFT);
        dd($abc);
        die();
        $qq_group = DB::table('qq_group')->get();
        foreach ($qq_group as $key => $value) {
            $user = User::where(['old_id' => $value->id])->where('id', '<', 10000)->first();
            if ($user) {
                $user->name = $value->user_nicename;
                $user->save();
            }
        }

        die;
        $user = UserCapital::get();
        foreach ($user as $key => $value) {
            UserIntegralLog::addUserIntegralLog($value->user_id, '初始化积分为20', env('UserIntegral'), 0, 1, $refuse = '');
        }
        die;
        $goodsQuery = DB::table('goods')
            ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
            ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
            ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
            ->leftjoin('users', 'goods.userid', '=', 'users.id')
            ->select('users.name as username',
                'goods.id', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.commissiontype', 'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.origprice', 'goods.voucherprice', 'goods.created_at', 'goods.goodstype',
                'goods_coupon.couponlink', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.reduceprice',
                'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.todaysales',
                'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype')
            ->orderBy('id', 'desc')
            ->limit(100);  //获取前100条数据
        $data = DB::table(DB::raw("({$goodsQuery->toSql()}) as goodsQuery"))
            ->orderBy('id', 'desc')
            ->paginate(env('LIMIT'));//从中拿去10条
        dd($data);
        die;

        $users = DB::connection('mysql_old')->select("SELECT * FROM  rm_users where  id<20");
        foreach ($users as $key => $value) {
            if ($value->avatar) {
                $upload_image = env('OLD_HTTP_URL') . $value->avatar;
                $image_url = \App\Http\Controllers\ImageController::uploadUrlImageOne($upload_image);
                $avater = $image_url ? $image_url : '';
            } else {
                $avater = '';
            }
            $is_set_user = User::where(['phone' => $value->mobile])->first();
            if ($is_set_user) {
                continue;
            }
            $user_id = User::insertGetId([
                'phone' => $value->mobile,
                'name' => $value->user_nicename,
                'email' => $value->user_email,
                'password' => Hash::make($value->user_pass),
                'signature' => $value->signature,
                'qq' => '',
                'avatar' => $avater,
                'created_at' => $value->create_time,
            ]);
            UserCapital::insert([
                'voucher_number' => $value->coin,
                'user_id' => $user_id,
                'integral' => $value->jifen,
                'created_at' => date('Y-m-d H:i:s', time())
            ]);
            if ($value->canfangdan) {
                $users_audit = DB::connection('mysql_old')->select("SELECT * FROM  rm_fangdaninfo  WHERE `uid`={$value->id} order by  id desc limit 1;");
                if ($users_audit) {
                    $users_audit = $users_audit[0];
                    UserSubmitAudit::insert([
                        'uid' => $user_id,
                        'state' => $users_audit->status,
                        'qq' => $users_audit->contactqq,
                        'content' => $users_audit->desc,
                        'phone' => $value->mobile,
                        'created_at' => date('Y-m-d H:i:s', time())
                    ]);
                }
            }
            Log::info('更新 old user' . $user_id);
        }
        die;
        $qq_group = DB::table('qq_group')->skip(1)->take(2)->get();
        foreach ($qq_group as $key => $value) {
            $user_id = User::insertGetId([
                'name' => $value->user_nicename,
                'avatar' => $value->avatar,
                'signature' => $value->signature,
                'qq' => $value->qq,
                'password' => $value->qq,
            ]);
            UserCapital::insert([
                'voucher_number' => env('Voucher_Default_Give'),
                'user_id' => $user_id,
                'integral' => env('UserIntegral')
            ]);
            UserSubmitAudit::insert([
                'uid' => $user_id,
                'state' => 1,
                'qq' => $value->qq,
            ]);
            UserAuth::insert([
                'user_id' => $user_id,
                'status' => 1,
                'channel_info' => $value->centifi_info,
            ]);
            UserKillStatus::insert([
                'user_id' => $user_id,
                'status' => 1,
            ]);
        }
        //


        dd(Auth::id());

        $keyword = [["key" => 1, "value" => "哈哈"], ["key" => 2, "value" => "哈哈"]];
        dd(json_encode($keyword));
        $array = array(
            array('img1' => '/web/goods/image_453de29c580a6319ed759b0fbebda196.jpg'),
            array('img2' => '/web/goods/image_453de29c580a6319ed759b0fbebda196.jpg'),
            array('img3' => '/web/goods/image_453de29c580a6319ed759b0fbebda196.jpg')
        );
        dd(json_decode('["\u6de1\u5316\u8272\u6591","\u63d0\u4eae\u80a4\u8272","\u51c0\u5316\u808c\u80a4","\u6539\u5584\u7c97\u7cd9"]'));
        //$keyword = json_decode();

        echo phpinfo();
        die;
    }

    public function getKillField()
    {
        $kill_field = GoodsKill::kill_field_info();
        return json_encode(['code' => 0, 'msg' => '获取成功!', 'data' => $kill_field]);

    }

    /**
     * 获取用户认证状态
     * @return string
     */
    public function getUserKillStatus()
    {
        $users_kill_status = UserKillStatus::where(['user_id' => Auth::id(), 'status' => 1])->first();
        if ($users_kill_status) {
            return json_encode(['code' => 0, 'msg' => '用户具有秒杀权限', 'data' => '']);
        } else {
            return json_encode(['code' => 1, 'msg' => '用户暂无秒杀权限', 'data' => '']);
        }
    }


    public function updateStatisticsData()
    {
        /*        $user_num = Goods::get()->groupBy('userid')->count();
                $user = StatisticsUser::first();
                $user->order_user = $user_num;
                $user->save();//保存已发单用户数量*/
        $number = StatisticsGoodsInfo::count();
        if ($number <= 4) {
            DB::table('statistics_goods_info')->truncate();
            $info_1 = StatisticsGoodsInfo::lastModelStart(0);
            $info_2 = StatisticsGoodsInfo::lastModelStart(1);
            $info_3 = StatisticsGoodsInfo::lastModelStart(2);
            $info_4 = StatisticsGoodsInfo::lastModelStart(3);
            DB::table('statistics_goods_info_log')->truncate();
            $gid_1 = Goods::where(['goodstype' => 0])->orderBy('id', 'desc')->first();
            $gid_1 = $gid_1 ? $gid_1->id : 0;
            $gid_2 = Goods::where(['goodstype' => 1])->orderBy('id', 'desc')->first();
            $gid_2 = $gid_2 ? $gid_2->id : 0;
            $gid_3 = Goods::where(['goodstype' => 2])->orderBy('id', 'desc')->first();
            $gid_3 = $gid_3 ? $gid_3->id : 0;
            StatisticsGoodsInfoLog::saveGoodsInfoLog(-1, 0, $gid_1, 0, $info_1, -1);
            StatisticsGoodsInfoLog::saveGoodsInfoLog(-1, 1, $gid_2, 0, $info_2, -1);
            StatisticsGoodsInfoLog::saveGoodsInfoLog(-1, 2, $gid_3, 0, $info_3, -1);
            StatisticsGoodsInfoLog::saveGoodsInfoLog(-1, 3, 0, 0, $info_4, -1);
            dd('数据更新完毕');
        } else {
            dd('数据不是初始数据,暂不能更新');
        }
    }

}